package com.yiwei.zhh.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;


import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yiwei.zhh.R;
import com.yiwei.zhh.adapter.TabsAdapter;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.HuaKouBean;
import com.yiwei.zhh.api.bean.LiMuKeyBean;
import com.yiwei.zhh.api.bean.LiMuSignBean;
import com.yiwei.zhh.api.bean.LiMuTokenBean;
import com.yiwei.zhh.api.bean.OtherIdentityBean;
import com.yiwei.zhh.api.bean.RepayStatusDialogBean;
import com.yiwei.zhh.api.bean.ZhiMaCertBean;
import com.yiwei.zhh.api.callback.SelectMoneyContract;
import com.yiwei.zhh.api.requestInfo.SelectMoneyRequest;
import com.yiwei.zhh.constant.UserGlobal;
import com.yiwei.zhh.event.ChangeHomePagerEvent;
import com.yiwei.zhh.event.DialogDismissEvent;
import com.yiwei.zhh.event.SelectMoneyEvent;

import com.yiwei.zhh.fragment.AllIdentityFragment;
import com.yiwei.zhh.fragment.FragmentV3Home;
import com.yiwei.zhh.fragment.MainHomePrizeV2Fragment;
import com.yiwei.zhh.fragment.V3DiscoverSecFragment;
import com.yiwei.zhh.fragment.V3MyFragment;
import com.yiwei.zhh.impl.RepayInfoImpl;
import com.yiwei.zhh.info.PhoneInfo;
import com.yiwei.zhh.model.AlertModel;
import com.yiwei.zhh.model.CertificationBasicsModel;
import com.yiwei.zhh.model.DealBeforeV3Model;
import com.yiwei.zhh.model.DealTypeModel;
import com.yiwei.zhh.model.DealTypesModel;
import com.yiwei.zhh.model.InitAppModel;
import com.yiwei.zhh.model.RepayModel;
import com.yiwei.zhh.model.ResponseModel;
import com.yiwei.zhh.util.DisplayUtil;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.PreferenceUtils;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.event.OnHomeEventMsg;
import com.yiwei.zhh.impl.UserInfoImpl;
import com.yiwei.zhh.http.InfoCallBack;
import com.yiwei.zhh.model.UserModel;
import com.yiwei.zhh.util.FileUtils;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.BottomIconText;
import com.yiwei.zhh.view.CircularProgress;
import com.yiwei.zhh.view.Dialog;
import com.yiwei.zhh.view.DialogQueue;
import com.yiwei.zhh.view.HomeViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.bean.MessageEvent;
import kangcheng.com.lmzx_android_sdk_v10.bean.SignEvent;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSDK;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.DataCallBack;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.ObservableManager;


public class MainActivityNew extends PermissionActivity implements SelectMoneyContract.View, AMapLocationListener, DataCallBack {

    //    private FragmentTabHost mTabhost;
//    private LayoutInflater mInflater;
//    private List<TabModel> mTabs = new ArrayList<>(3);//用于存放tab

    private static long exitTime = 0;
    private MainActivityNew.DownloadBroadcastReceiver receiver;
    private MainActivityNew.DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    private MaterialDialog materialDialog;
    private long lastDownloadId = 0;
    private int currentIndex = 0;
    private PhoneInfo phoneInfo;
    /*顶部状态栏*/
    RelativeLayout mTitleBar;
    TextView mTitle;

    ImageView mRightImage;
    private CircularProgress loading;
    private boolean isShowDialog = false;
    private HomeViewPager pager;
    private TabLayout tabBottom;
    //    private final int[] iconRes = new int[]{R.drawable.selector_icon_slot_card, R.drawable.selector_icon_identity, R.drawable.selector_icon_repay, R.drawable.selector_icon_earn_money, R.drawable.selector_icon_me};
//    private final String[] bottomTitle = new String[]{"借款", "认证", "发现", "赚钱", "我的"};
    private final int[] iconRes = new int[]{R.drawable.selector_icon_slot_card, R.drawable.selector_icon_identity, R.drawable.selector_icon_earn_money, R.drawable.selector_icon_me};
    private final String[] bottomTitle = new String[]{"借款", "认证", "赚钱", "我的"};
    private Fragment[] fragments;
    private TabLayout.OnTabSelectedListener tabListener;
    private SelectMoneyRequest api;
    private List<OtherIdentityBean> otherList;
    private List<Map<String, String>> appList;
    private String deal_id;
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private FragmentV3Home mainHomeFragment;
    private String loanType = "1";
    private String dealId, mMoney, overdue;
    private float newMoney;
    private float balance;
    private float Month_need_all_repay_money;
    private boolean isRepay = false;
    private boolean isFirstDialog = true;
    private ArrayList<String> explainList;
    private String notice_sn;
    private int selectPoi = 0;
    private boolean isSelectPoi;
    private boolean isInit;
    public boolean initSuccess;
    private boolean isFail = false;
    private AllIdentityFragment allIdentityFragment;
    public final static String SUCCESS = "0";
    public final static String LOGING_SUCCESS = "2";

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_new);
        initBar();
        isSelectPoi = getIntent().getBooleanExtra("is_select", false);
        isInit = getIntent().getBooleanExtra("is_init", true);
        boolean isNeedGesture = getIntent().getBooleanExtra("gesture", false);
        if (isNeedGesture) {
            setIsNeedCheckLogout(false);
        }
        //注册订阅者
        EventBus.getDefault().register(this);
        initBtn();
        initTab();
        api = SelectMoneyRequest.create();
        api.attachView(this);
        getUserInfo();
        if (!isInit) {
            api.initApp();
        }
    }


    private void appInit() {
        api.initApp();
    }

    public void initLocation() {
        showLoading(true);
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setNeedAddress(true);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }


    // dialog队列FIFO弹出
    private Queue<android.app.Dialog> dialogQueue = new LinkedList<>();
    private android.app.Dialog currentDialog = null; // 当前显示的对话框

    private void showDialog(android.app.Dialog dialog) {
        if (dialog != null) {
            dialogQueue.offer(dialog);
        }
        if (currentDialog == null) {
            currentDialog = dialogQueue.poll();
            if (currentDialog != null) {
                currentDialog.show();
                currentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        api.submitAlert(dialogId);
                        currentDialog = null;
                        showDialog(null);
                    }
                });
            }
        }
    }


    /**
     * 初始化按钮
     */
    private void initBtn() {
        mTitleBar = (RelativeLayout) findViewById(R.id.titlebar);
        mTitle = (TextView) findViewById(R.id.top_title_text);
//        mRightText = (TextView) findViewById(R.id.top_right_text);
//        doc = (TextView) findViewById(R.id.doc);
        loading = (CircularProgress) findViewById(R.id.progressBar);
        pager = (HomeViewPager) findViewById(R.id.viewpager);
        tabBottom = (TabLayout) findViewById(R.id.tab_bottom);

//        int size = DisplayUtil.dip2px(this, 28);
        for (int i = 0; i < iconRes.length; i++) {
            BottomIconText icon = (BottomIconText) getLayoutInflater().inflate(R.layout.view_text_icon, tabBottom, false);
            icon.setDrawable(ResourcesCompat.getDrawable(getResources(), iconRes[i], null));
            icon.setTextString(bottomTitle[i], 12, 0xFF191919);
            tabBottom.addTab(tabBottom.newTab().setCustomView(icon));
        }
        pager.setOffscreenPageLimit(2);
        mainHomeFragment = new FragmentV3Home();
//        MyLoanFragment mainLoanFragment = new MyLoanFragment();
        MainHomePrizeV2Fragment mainHomePrizeFragment = new MainHomePrizeV2Fragment();
        allIdentityFragment = new AllIdentityFragment();
//        V3DiscoverSecFragment v3DiscoverFragment = new V3DiscoverSecFragment();
        V3MyFragment mainMeFragment = new V3MyFragment();
        fragments = new Fragment[]{mainHomeFragment, allIdentityFragment, mainHomePrizeFragment, mainMeFragment};
        tabListener = new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if ((tab.getPosition() == 2 || tab.getPosition() == 3 || tab.getPosition() == 1) && !UserGlobal.checkLogin()) {
                    tabBottom.getTabAt(selectPoi).select();
                    Util.startActivity(MainActivityNew.this, V3LoginByCodeActivity.class);
                } else {
                    selectPoi = tab.getPosition();
                    pager.setCurrentItem(tab.getPosition());
                }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        };
    }

    private void initTab() {

        pager.setAdapter(new TabsAdapter(getSupportFragmentManager(), fragments));
        pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabBottom));
        tabBottom.getTabAt(0).select();
        tabBottom.addOnTabSelectedListener(tabListener);
        if (isSelectPoi) {
            pager.setCurrentItem(2);
        }
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 98) {
                        gotoUpdate();
                    } else if (result.getStatus() == 1) {
                        UserGlobal.saveUserInfo(result);
                    }

                });
    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(OnHomeEventMsg msg) {
        Map<String, String> map = msg.getMsg();
        String type = msg.getMsg().get("type");
        if (type.equals(Const.SendType.SWITCH_PAGE)) { //切换界面

            currentIndex = Integer.parseInt(map.get("currentIndex"));
            pager.setCurrentItem(currentIndex);
            if (currentIndex == 2) {
                api.initApp();
            }
        } else if (type.equals(Const.SendType.LOGIN) || type.equals(Const.SendType.LOGOUT) || type.equals(Const.SendType.UPDATE)) { //登录，退出登录，更新数据
            getUserInfo();
        } else if (type.equals(Const.SendType.UPDATE_REPAY)) {  //更新
//            pager.setCurrentItem(1);
            pager.setCurrentItem(0);
        }
        if (type.equals(Const.SendType.REGISTER)) {
            getUserInfo();
            pager.setCurrentItem(0);
            Dialog.showRegisterTipDialog(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectMoney(ChangeHomePagerEvent msg) {
        pager.setCurrentItem(msg.poi);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectMoney(SelectMoneyEvent msg) {
//        api.getDealTypeInfo();
//        修改逻辑，获取借钱前查询
        api.getDealBefore();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtil.makeText(this,
                        getResources().getString(R.string.exit_text),
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                this.finish();
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void gotoUpdate() {
        if (materialDialog != null && materialDialog.isShowing()) {
            return;
        }
        checkUpdate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        gotoUpdate();
        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        if (TextUtils.isEmpty(version))
            return;
        String versionName = Util.getVersion(this);
        versionName = versionName.replace("", "");
        String versionNew = version.replace("", "");

        if (compareVersion(versionNew, versionName) > 0) {
            return;
        }

        if (UserGlobal.checkLogin()) {
            if (!PreferenceUtils.getBoolean(this, "show_prize_dialog", false)) {
                Dialog.showPrizeDialog(this, new Dialog.DialogClickListener() {
                    @Override
                    public void confirm() {
                        pager.setCurrentItem(2);
                    }
                });
                PreferenceUtils.putBoolean(this, "show_prize_dialog", true);
            } else {
                if (dialogQueue.size() != 0) {
                    return;
                }
                api.getAlert();
            }
        }


    }

    @Override
    public void signData(SignEvent signEvent) {
        String sign = signEvent.getSignStr();//r3qUEj6PhkTz8odjHC0OYTXbtlSxqWyQ  //1.收到sdk传来的字符串
        getSign(sign);
    }

    public String bizType;

    @Override
    public void messageData(MessageEvent event) {
        MessageEvent test = (MessageEvent) event;
//            Log.i("dasdadsadsadsasa", "code" + test.getCode() + ",message" + test.getMessage() + ",token" + test.getToken() + ",function" + test.getFunction() + ",hasmap" + test.getHashMap().toString());

        if (SUCCESS.equals(((MessageEvent) event).getCode())) {
            //具体哪个业务,参看文档的相关业务类型做处理
            int function = ((MessageEvent) event).getFunction();
            //服务密码
            if (function == Fuction.LMZXSDKFunctionMobileCarrie) {
                //...

            }
            //登录成功处理
        } else if (LOGING_SUCCESS.equals(((MessageEvent) event).getCode())) {
            //可以获取token值,记录提交请求,或者忽略掉
            isFail = false;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //查询失败
        } else {
            isFail = true;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //失败处理,可忽略
//            Log.i("dadasdda", "失败code：" + ((MessageEvent) event).getCode() + "\ntoken=" + ((MessageEvent) event).getToken());
//            Intent intent = new Intent(getContext(), MyIdentityActivity.class);
//            startActivity(intent);
        }
    }

    public void getKey(String deal_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuKeyBean bean = new LiMuKeyBean();
        bean.deal_id = deal_id;
        Api.api_service.getLiMuKey(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    //    初始化立木
                    if (result.getStatus() == 1) {
                        Application.getInstance().LmsdkInit(result.getData().getKey(), result.getData().getUid());
                        LmzxSDK sdk = LmzxSdkImpl.getInstance();
                        sdk.registEvent(this);
                        sdk.setTextStyle(this, 0xFF4a4a4a);
                        sdk.setButtonStyle(this, 0xFF4C81FF);
                        sdk.setPageBack(this, 0xFFf4f4f4);
                        sdk.setBannerTextColor(this, 0xFFFFFFFF);
                        initSuccess = true;
//                        Log.i("dassdasdadas", "运营了");
                    }
                });
    }

    public void getSign(String params) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuSignBean bean = new LiMuSignBean();
        bean.params = params;
        Api.api_service.getSign(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("sign", result.getSign());
                    //Log.i("signString", "加签结果" + secondSign);
                    ObservableManager.getInstance().doLogic("sign", hashMap); //加签结果传给sdk。key值必须是"sign"。
                });
    }


    public void uploadToken(String deal_id, String token, String biztype) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        LiMuTokenBean bean = new LiMuTokenBean();
        bean.deal_id = deal_id;
        bean.token = token;
        bean.biztype = biztype;
        Api.api_service.uploadToken(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1 && !isFail) {
                        allIdentityFragment.getMyCertification();
                        ToastUtil.makeText(this, "认证成功", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    public void getHuaKouInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        HuaKouBean bean = new HuaKouBean();
        bean.deal_id = UserGlobal.getDealId();
        Api.api_service.getHuaKouResult(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    // -1 - 无还款信息 0 - 还款失败、1 - 还款成功、2 - 还款审核中
                    switch (result.data.repay_staus) {
                        case "-1":
                            Util.startActivity(this, V3RepayMoneyNewActivity.class);
                            break;
                        case "0":
                            Util.startActivity(this, V3RepayMoneyNewActivity.class);
                            break;
                        case "1":
                            Dialog.showRepaySuccessDialog(this, new Dialog.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    mainHomeFragment.getIndex();
                                }

                                @Override
                                public void cancel() {
                                    mainHomeFragment.getIndex();
                                }
                            });
                            break;
                        case "2":
                            Util.startActivity(this, RepayStatusActivity.class);
                            break;
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播监听
        // if (homeView != null) homeView.unRegisterBoradcastReceiver();
        LmzxSdkImpl.getInstance().unRegistEvet();
        EventBus.getDefault().unregister(this);
        if (receiver != null) unregisterReceiver(receiver);
        if (downloadObserver != null)
            getContentResolver().unregisterContentObserver(downloadObserver);
    }


    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (b) {
            if (loading != null) {
                loading.setVisibility(View.VISIBLE);
                tabBottom.setEnabled(false);
            }
        } else {
            if (loading != null) {
                loading.setVisibility(View.GONE);
                tabBottom.setEnabled(true);
            }
        }
    }


    //----------------  版本更新  --------------------//

    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", Const.DOWNLOAD_URL);


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {


                //注册下载监听
                receiver = new MainActivityNew.DownloadBroadcastReceiver();
                registerReceiver(receiver, new IntentFilter(
                        DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                showInstallDialog();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private void showInstallDialog() {
        if (!isShowDialog) {
            isShowDialog = true;
            String updateContent = PreferenceUtils.getString(this, "upgrade_msg", "");
            if (updateContent.contains("{current_version}"))
                updateContent = updateContent.replace("{current_version}", Util.getVersion(this));
            if (updateContent.contains("{lastest_version}"))
                updateContent = updateContent.replace("{lastest_version}", PreferenceUtils.getString(this, "lastest_version", "1.0.0"));
            if (!Util.isWifi(this))
                updateContent = updateContent + getResources().getString(R.string.update_content);


            String leftBtn;
            if (PreferenceUtils.getInt(this, "forced_upgrade", 0) == 1)
                leftBtn = "";
            else leftBtn = getResources().getString(R.string.update_next_time);

            Dialog.showDefaultDialog(this, getResources().getString(R.string.update_title), updateContent, leftBtn, getResources().getString(R.string.update_now), false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    isShowDialog = false;
//                    showLoading(true);
                    if (!canDownloadState()) {
                        Dialog.showDefaultDialog(MainActivityNew.this, getResources().getString(R.string.tip), "请开启下载服务权限", getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                String packageName = "com.android.providers.downloads";
                                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + packageName));
                                startActivity(intent);
                            }

                            @Override
                            public void cancel() {
                                showInstallDialog();
                            }
                        });
                        return;
                    }
                    downloadApp();
                }

                @Override
                public void cancel() {

                }
            });
        }
    }


    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(MainActivityNew.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(MainActivityNew.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Const.PermissionType.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 安装app 6.0以上
     */
    private void installApp(long myDwonloadID) {
        try {


            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = queryDownloadedApk(this);
                Uri apkUri = FileProvider.getUriForFile(MainActivityNew.this, "com.yiwei.zhh.fileprovider", file);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                startActivity(install);
            } else {
                if (Build.VERSION.SDK_INT >= 23) {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        File apkFile = queryDownloadedApk(this);
                        install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        Uri downloadFileUri = manager
                                .getUriForDownloadedFile(myDwonloadID);
                        install.setDataAndType(downloadFileUri,
                                "application/vnd.android.package-archive");
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(install);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        long downloadId = PreferenceUtils.getLong(context, "downloadId", 0);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }

    /**
     * 初始化下载
     */
    private void initDownloadManager() {
        String url = PreferenceUtils.getString(this, "download_url", Const.DOWNLOAD_URL);
        if (TextUtils.isEmpty(url)) return;

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(MainActivityNew.this)
                    .title(R.string.update_title)
                    .content(R.string.downloading_text)
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
            request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, Const.APP_NAME);
//            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription(getResources().getString(R.string.app_name)
                    + getResources().getString(R.string.downloading_text));

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(this, "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new MainActivityNew.DownloadChangeObserver(null);
            getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void showError() {
        showLoading(false);
    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }


    @Override
    public void getDealTypeInfoSuccess(DealTypesModel item) {
//        Intent intent = new Intent(this, SelectMoneyActivity.class);
//        intent.putExtra(Const.KEY.SELECT_MONEY, item);
//        startActivity(intent);
//        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
    }

    private String dialogId = "";
    private boolean tongxunlu = true;

    @Override
    public void getAlertSuccess(AlertModel item) {
//        version              版本更新
//        email                邮箱认证
//        overdue            逾期提示
//        upgrade           升级提示
        if (item.getStatus() == 0 || item.getStatus() == 99 || item.getStatus() == 98) {
            return;
        }
        dialogId = item.data.id;
        if (item.data.name.equals("version")) {
            dialogQueue.add(DialogQueue.showDefaultDialog(this, item.data.content.title, item.data.content.text, "", "知道了", false, new DialogQueue.DialogDefaultClickListener() {
                @Override
                public void confirm() {

                }

                @Override
                public void cancel() {

                }
            }));
        } else if (item.data.name.equals("systemNotice")) {
            dialogQueue.add(DialogQueue.showDefaultDialog(this, item.data.content.title, item.data.content.text, "", "知道了", false, new DialogQueue.DialogDefaultClickListener() {
                @Override
                public void confirm() {

                }

                @Override
                public void cancel() {

                }
            }));
        } else if (item.data.name.equals("adjust")) {
            if (item.data.content.remark.equals("auth_bankcard")) {
                dialogQueue.add(DialogQueue.gotoBankIdentity(this, new DialogQueue.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        Util.startActivity(MainActivityNew.this, BankIdentityActivity.class);
                    }

                    @Override
                    public void cancel() {

                    }
                }));

            }

        } else if (item.data.name.equals("email")) {
            dialogQueue.add(DialogQueue.showRegisterTipDialog(this));
        } else if (item.data.name.equals("renewal")) {
            dialogQueue.add(DialogQueue.gotoXuQi(this, item.data.content.text));
        } else if (item.data.name.equals("eliteSpreads")) {
            dialogQueue.add(DialogQueue.showMoneyArriveDialog(this, new DialogQueue.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Util.startActivity(MainActivityNew.this, V3MyFundActivity.class);
                }

                @Override
                public void cancel() {

                }
            }));
        } else if (item.data.name.equals("loans")) {
            dialogQueue.add(DialogQueue.goGongxi(this, item.data.content.html));
        } else if (item.data.name.equals("repay")) {
            dialogQueue.add(DialogQueue.goHuankuan(this, item.data.content.html));
        } else if (item.data.name.equals("overdue")) {
            dialogQueue.add(DialogQueue.showFriendlyTipDialog(this));
        } else if (item.data.name.equals("upgrade")) {
            PreferenceUtils.putInt(this, Const.KEY.LEVEL, Integer.valueOf(item.data.content.level_id));
            PreferenceUtils.putInt(this, Const.KEY.LEVEL_POINT, Integer.valueOf(item.data.content.next_level_point_diff));
            dialogQueue.add(DialogQueue.showLevelUpDialog(this, item.data.content.amount));
        } else if (item.data.name.equals("supplyinfo")) {
//            通讯录
            if (!tongxunlu) {
                return;
            }
            tongxunlu = false;
            otherList = item.data.content.lists;
            deal_id = item.data.content.deal_id;
            dialogQueue.add(DialogQueue.needOtherData(this, new DialogQueue.DialogDefaultClickListener() {
                @Override
                public void confirm() {
//                        Util.startActivity(MainActivityNew.this, V3AllIdentityActivity.class);
                    EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                }


                @Override
                public void cancel() {

                }
            }));

//            if (item.data.content.tongxunlu.equals("0")) {
//                dialogQueue.add(DialogQueue.needOtherData(this, new DialogQueue.DialogDefaultClickListener() {
//                    @Override
//                    public void confirm() {
////                        Util.startActivity(MainActivityNew.this, V3AllIdentityActivity.class);
//                        EventBus.getDefault().post(new ChangeHomePagerEvent(1));
//                    }
//
//
//                    @Override
//                    public void cancel() {
//
//                    }
//                });
//            } else {
//                Dialog.needOtherData(this, new Dialog.DialogClickListener() {
//                    @Override
//                    public void confirm() {
//                        EventBus.getDefault().post(new ChangeHomePagerEvent(1));
//                    }
//                });
//                return;
//            }


        }
        showDialog(null);
    }


    private void uploadTongxunlu() {
        phoneInfo = new PhoneInfo(this);
        checkContactsPermission();
    }


    /**
     * 获取通讯录
     */
    private void checkContactsPermission() {
        //判断是否6.0
        checkPermission(new PermissionActivity.CheckPermListener() {
            @Override
            public void superPermission() {
//                showLoading(true);
                phoneInfo.getContactsList(new InfoCallBack() {
                    @Override
                    public void onSuccess(final Object o) {
//                        contactList = (List<Map<String, String>>) o
//                        getAppList((List<Map<String, String>>) o);
                        api.addResslist(deal_id, (List<Map<String, String>>) o, null, null, null);
                        if (otherList != null && otherList.size() != 0) {
                            dialogQueue.add(DialogQueue.gotoOtherIdentity(MainActivityNew.this, new DialogQueue.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    EventBus.getDefault().post(new ChangeHomePagerEvent(1));
                                }


                                @Override
                                public void cancel() {

                                }
                            }, otherList));
                            showDialog(null);
                        }
                    }

                    @Override
                    public void onFailure(String cause) {
                        ToastUtil.makeText(MainActivityNew.this, cause).show();
                    }
                });
            }
        }, R.string.contact_p, R.string.get_contact, android.Manifest.permission.WRITE_CONTACTS, android.Manifest.permission.READ_CONTACTS);
    }


    @Override
    public void submitAlertSuccess() {

    }

    @Override
    public void addResslistSuccess() {

    }

    @Override
    public void initAppSuccess(InitAppModel item) {
        showLoading(false);
        UserGlobal.saveInitInfo(item);
    }

    @Override
    public void getDealBefore(DealBeforeV3Model item) {
        switch (item.data.step) {
            case 0:
                Util.startActivity(this, SelectMoneyV3Activity.class);
                break;
            case 1:
                api.getOneKeyIdentity();
                break;
            case 2:
                Dialog.needOtherData(this, new Dialog.DialogClickListener() {
                    @Override
                    public void confirm() {
                        if (item.data.uplists != null && item.data.uplists.size() != 0) {
                            Intent intent = new Intent();
                            switch (item.data.uplists.get(0).remark) {
                                case Const.IdentityType.yunyin:
                                    intent.setClass(MainActivityNew.this, V3YunYingIdentityActivity.class);
                                    break;
                                case Const.IdentityType.contacts:
                                    intent.setClass(MainActivityNew.this, V3AddressIdentityActivity.class);
                                    break;
                                case Const.IdentityType.realname:
                                    intent.setClass(MainActivityNew.this, V3IdcardIdentityActivity.class);
                                    break;
                                case Const.IdentityType.taobao:
                                    intent.setClass(MainActivityNew.this, V3TaobaoIdentityActivity.class);
                                    break;
                                case Const.IdentityType.face_detect:
                                    intent.setClass(MainActivityNew.this, V3FaceIdentityOneActivity.class);
                                    break;
                                case Const.IdentityType.xuexin:
                                    intent.setClass(MainActivityNew.this, V3XueXinIdentityActivity.class);
                                    break;
                                case Const.IdentityType.bankcard:
                                    intent.setClass(MainActivityNew.this, StepBankIdentityActivity.class);
                                    break;
                            }
                            intent.putExtra(Const.KEY.SOME_IDENTITY_KEY, item.data.uplists);
                            startActivity(intent);
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                        }
                    }
                });
                break;
            case 3:
                Util.startActivity(this, SelectMoneyV3Activity.class);
                break;
        }
    }

    @Override
    public void getOneKeyIdentitySuccess(CertificationBasicsModel item) {
        if (item.data != null && item.data.size() != 0) {
            if (item.data.get(0).iscert.equals("0") || item.data.get(0).iscert.equals("3")) {
                Intent intent = new Intent();
                switch (item.data.get(0).remark) {
                    case Const.IdentityType.yunyin:
                        intent.setClass(MainActivityNew.this, V3YunYingIdentityActivity.class);
                        break;
                    case Const.IdentityType.contacts:
                        intent.setClass(MainActivityNew.this, V3AddressIdentityActivity.class);
                        break;
                    case Const.IdentityType.realname:
                        intent.setClass(MainActivityNew.this, V3IdcardIdentityActivity.class);
                        break;
                    case Const.IdentityType.taobao:
                        intent.setClass(MainActivityNew.this, V3TaobaoIdentityActivity.class);
                        break;
                    case Const.IdentityType.face_detect:
                        intent.setClass(MainActivityNew.this, V3FaceIdentityOneActivity.class);
                        break;
                    case Const.IdentityType.xuexin:
                        intent.setClass(MainActivityNew.this, V3XueXinIdentityActivity.class);
                        break;
                    case Const.IdentityType.bankcard:
                        intent.setClass(MainActivityNew.this, StepBankIdentityActivity.class);
                        break;
                }
                intent.putExtra(Const.KEY.ONE_KEY, item.data);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);


            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        showLoading(false);
        if (amapLocation != null) {
            ToastUtil.makeText(this, "定位成功").show();
            PreferenceUtils.getBoolean(this, "is_locat", true);
            mainHomeFragment.setAddress(amapLocation.getCity());
            PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LAT, amapLocation.getLatitude());
            PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LNG, amapLocation.getLongitude());
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                appInit();
            } else {
                appInit();
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
            }
        }
    }

    //用于显示下载进度
    private class DownloadChangeObserver extends ContentObserver {

        private DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
//                    materialDialog.dismiss();
                }
            }
        }


    }

    private int p = 10;

    /**
     * 下载广播
     */
    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            try {
                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                    showLoading(false);

                    long myDwonloadID = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                    long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                    if (refernece == myDwonloadID) {
                        manager = (DownloadManager) context
                                .getSystemService(DOWNLOAD_SERVICE);

//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                        else
                        installApp(myDwonloadID);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Const.PermissionType.WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(MainActivityNew.this, getResources().getString(R.string.get_permission_fail), Toast.LENGTH_SHORT).show();
            }
        }
    }


    public void getZhiMaCertInfo() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        Api.api_service.getZhiMaYuan().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    doVerify(result.data.url);
                });


    }

    private void doVerify(String url) {
        if (hasApplication()) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
//            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
//            builder.append(URLEncoder.encode(url));
            builder.append(url);
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
//            isVerify = true;
        } else {
            //处理没有安装支付宝的情况
            Dialog.showDefaultDialog(this, "", getString(R.string.download_alipay_tishi), getString(R.string.forget_it), getString(R.string.good), false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Intent action = new Intent(Intent.ACTION_VIEW);
                    action.setData(Uri.parse("https://m.alipay.com"));
                    startActivity(action);
                }

                @Override
                public void cancel() {

                }
            });
        }
    }

    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

}
